<template>
  <div
    class="contents"
    :class="[
      currentStatus === 'register' ? 'contents-register' : 'contents-login'
    ]"
  >
    <div class="title" v-if="!isNesting">
      {{ currentStatus === "register" ? "注册" : "登录" }}
    </div>
    <c-form
      v-model="form"
      ref="form"
      :data="formData"
      :rules="rules"
      :showLabel="false"
      @validate="validate"
      @pressEnter="pressEnter"
    >
      <template v-slot:captchaCode="{ change }">
        <a-input-group compact>
          <a-input
            v-model="form.captchaCode"
            ref="userNameInput"
            style="width: 65%"
            placeholder="请输入图形验证码"
            @change="change('captchaCode')"
          >
            <c-icon type="tupian" slot="prefix" size="14" />
          </a-input>
          <img
            :src="graphicUrl"
            style="width: 35%"
            class="cursor-pointer graphicCode"
            @click="getCaptchaCode"
            alt=""
            v-if="graphicUrl"
          />
          <c-button type="primary" width="35%" @click="getCaptchaCode" v-else
            >获取验证码</c-button
          >
        </a-input-group>
      </template>
      <template v-slot:registerCode="{ change }">
        <a-input-group compact>
          <a-input
            v-model="form.registerCode"
            style="width: 65%"
            @change="change('registerCode')"
            placeholder="请输入验证码"
          >
            <template v-slot:prefix>
              <c-icon type="xiaoxi" size="14" />
            </template>
          </a-input>
          <c-button
            type="primary"
            width="35%"
            :loading="getRegisterCodeLoading"
            :disabled="getRegisterCodeDisabled"
            @click="getRegisterCode"
            >{{ getRegisterCodeText }}</c-button
          >
        </a-input-group>
      </template>
    </c-form>
    <div class="footer">
      <div class="top flex">
        <div class="agreement" v-if="currentStatus === 'register'">
          <a-checkbox v-model="checkedAgreement"></a-checkbox>
          我已阅读并同意
          <i class="cursor-pointer primary" @click="agreement">《用户协议》</i>
        </div>
        <div class="resetPassword" v-else>
          <i class="cursor-pointer primary" @click="resetPassword">忘记密码</i>
        </div>
      </div>
      <div class="bottom">
        <div class="submit">
          <a-space class="submit-space flex" direction="vertical" size="middle">
            <c-button
              type="primary"
              class="submit-btn"
              block
              :loading="submitLoading"
              @click="submit"
              :disabled="currentStatus === 'register' && !checkedAgreement"
              >{{
                currentStatus === "register" ? "立即注册" : "登录"
              }}</c-button
            >
            <c-button
              block
              class="back submit-btn"
              @click="toHome"
              v-if="!isNesting"
              >返回首页</c-button
            >
          </a-space>
        </div>
        <div class="toLogin tc" v-if="currentStatus === 'register'">
          已有账号，
          <router-link :to="{ name: 'login' }" class="primary"
            >前往登录</router-link
          >
        </div>
        <div class="toRegister tc" v-else>
          还没有账号？
          <router-link :to="{ name: 'register' }" class="primary"
            >免费注册</router-link
          >
        </div>
      </div>
    </div>
    <c-modal
      v-model="resetVisible"
      title="重置密码"
      @cancel="resetPasswordClose"
      :getContainer="true"
      noFooter
      destroyOnClose
      compact
    >
      <ResetPassword ref="resetPassword" @resetFinish="resetPasswordFinish" />
    </c-modal>
    <c-modal
      v-model="agreementVisible"
      width="700px"
      :closeable="false"
      title="大宗聚点商城用户注册协议"
      :getContainer="true"
    >
      <LoginAgreement style="height: 500px;overflow: auto;" />
      <!-- <a-spin :spinning="loginAgreementLoading"> -->
      <!-- <iframe
          ref="loginAgreement"
          :src="
            'https://h5.manytrader.net/userAgreement?time=' +
              new Date().getTime()
          "
          width="100%"
          height="500px"
          frameborder="0"
        ></iframe> -->

      <!-- </a-spin> -->
      <template v-slot:footer>
        <c-button type="primary" @click="agreementVisible = false"
          >确定</c-button
        >
      </template>
    </c-modal>
    <c-modal
      v-model="loginVisible"
      title="登录认证"
      noFooter
      centered
      destroyOnClose
      compact
      dialogClass="loginVerifyModal"
      @cancel="loginVerifyClose"
      :getContainer="true"
    >
      <c-form
        v-model="loginVerifyForm"
        ref="loginVerify"
        :data="loginVerifyFormData"
        :rules="loginVerifyRules"
        :showLabel="false"
        @submit="loginVerify"
      >
        <template v-slot:captchaCode="{ change }">
          <a-input-group compact>
            <a-input
              v-model="loginVerifyForm.captchaCode"
              ref="userNameInput"
              style="width: 65%"
              placeholder="请输入图形验证码"
              @change="change('captchaCode')"
            >
              <c-icon type="tupian" slot="prefix" size="14" />
            </a-input>
            <img
              :src="graphicUrl"
              style="width: 35%"
              class="cursor-pointer graphicCode"
              @click="getCaptchaCode"
              alt=""
              v-if="graphicUrl"
            />
            <c-button type="primary" width="35%" @click="getCaptchaCode" v-else
              >获取验证码</c-button
            >
          </a-input-group>
        </template>
        <template v-slot:registerCode="{ change }">
          <a-input-group compact>
            <a-input
              v-model="loginVerifyForm.registerCode"
              style="width: 65%"
              @change="change('registerCode')"
              placeholder="请输入验证码"
            >
              <template v-slot:prefix>
                <c-icon type="xiaoxi" size="14" />
              </template>
            </a-input>
            <c-button
              type="primary"
              width="35%"
              :loading="getRegisterCodeLoading"
              :disabled="getRegisterCodeDisabled"
              @click="getRegisterCode"
              >{{ getRegisterCodeText }}</c-button
            >
          </a-input-group>
        </template>
      </c-form>
    </c-modal>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import {
  sendRegisterCode,
  sendLoginVericode,
  registerCaptcha,
  loginCaptcha
} from "@/api/login/index.js";
import ResetPassword from "@/views/reset-password";
import LoginAgreement from "./loginAgreement";

const formLogin = [
  {
    label: "手机号",
    prop: "phone",
    prefix: "phone"
  },
  {
    label: "密码",
    prop: "password",
    type: "password",
    prefix: "mima1"
  }
];
const loginVerifyFormData = [
  {
    label: "手机号",
    prop: "phone",
    prefix: "phone",
    disabled: true
  },
  {
    label: "图形验证码",
    prop: "captchaCode",
    slot: "captchaCode"
  },
  {
    label: "验证码",
    prop: "registerCode",
    slot: "registerCode"
  },
  {
    label: " ",
    prop: "submit",
    type: "submit",
    submitText: "认证"
  }
];
const formRegister = [
  {
    label: "手机号",
    prop: "phone",
    prefix: "phone"
  },
  {
    label: "图形验证码",
    prop: "captchaCode",
    slot: "captchaCode"
  },
  {
    label: "验证码",
    prop: "registerCode",
    slot: "registerCode"
  },
  {
    label: " ",
    prop: "hidden1"
    // hidden: true
  },
  {
    label: " ",
    prop: "hidden2",
    inputType: "password"
  },
  {
    label: "密码",
    prop: "password",
    inputType: "password",
    prefix: "mima1"
  },
  {
    label: "推荐人",
    prop: "introducer",
    prefix: "tubiao302"
  }
];

export default {
  components: {
    ResetPassword,
    LoginAgreement
  },
  props: {
    // 是否嵌套在其他页面
    isNesting: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 当前状态
      currentStatus: undefined,
      form: {
        phone: "",
        captchaCode: "",
        registerCode: "",
        password: "",
        introducer: ""
      },
      loginVerifyForm: {
        phone: "",
        captchaCode: "",
        registerCode: ""
      },
      loginVisible: false,
      resetVisible: false,
      getRegisterCodeText: "获取验证码",
      getRegisterCodeLoading: false,
      getRegisterCodeDisabled: true,
      agreementVisible: false,
      checkedAgreement: true,
      rules: {
        phone: [
          { required: true, validator: this.$vd.phone, trigger: "change" }
        ],
        captchaCode: [
          { required: true, message: "请输入图形验证码", trigger: "change" }
        ],
        registerCode: [
          { required: true, message: "请输入验证码", trigger: "change" }
        ],
        password: [
          { required: true, validator: this.$vd.passWord, trigger: "change" }
        ]
      },
      loginVerifyRules: {
        captchaCode: [
          { required: true, message: "请输入图形验证码", trigger: "change" }
        ],
        registerCode: [
          { required: true, message: "请输入验证码", trigger: "change" }
        ]
      },
      graphicUrl: null,
      loginId: null,
      timer: null,
      loginVerifyFormData: loginVerifyFormData,
      submitLoading: false
      // loginAgreementLoading: false
    };
  },
  watch: {
    $route(to) {
      //   嵌套页默认显示登录界面
      this.currentStatus = this.isNesting ? "login" : this.$route.name;
      if (to.name === "register") {
        this.agreementVisible = true;
        this.getCaptchaCode();
      }
      this.$refs.form.resetFields();
      // 重置倒计时
      this.timer = null;
      this.getRegisterCodeText = "获取验证码";
      this.getRegisterCodeDisabled = false;
    }
  },
  computed: {
    formData() {
      let formData;
      if (this.currentStatus === "register") {
        formData = formRegister;
      } else {
        formData = formLogin;
      }
      return formData;
    }
  },
  methods: {
    ...mapActions(["login", "verifyLogin", "register", "setLoginInfo"]),
    // 密码框回车
    pressEnter() {
      this.submit();
    },
    resetPassword() {
      this.resetVisible = true;
    },
    agreement() {
      this.agreementVisible = true;
    },
    toHome() {
      this.$router.push({ name: "home" });
    },
    // 触发表单校验的回调事件
    validate(data) {
      if (data.prop === "phone") {
        if (data.status && this.getRegisterCodeText === "获取验证码") {
          this.getRegisterCodeDisabled = false;
        } else {
          this.getRegisterCodeDisabled = true;
        }
      }
    },
    // 获取图片验证码
    getCaptchaCode() {
      if (this.currentStatus === "register") {
        registerCaptcha().then(res => {
          this.graphicUrl = URL.createObjectURL(res);
        });
      } else {
        loginCaptcha().then(res => {
          this.graphicUrl = URL.createObjectURL(res);
        });
      }
    },
    // 发送短信验证码
    getRegisterCode() {
      this.getRegisterCodeLoading = true;
      if (this.currentStatus === "register") {
        let params = {
          captchaCode: this.form.captchaCode,
          phone: this.form.phone
        };
        sendRegisterCode(params)
          .then(() => {
            this.countdown();
            this.$message.success("短信发送成功");
            this.getRegisterCodeDisabled = true;
          })
          .catch(() => {
            this.getCaptchaCode();
          })
          .finally(() => {
            this.getRegisterCodeLoading = false;
          });
      } else {
        let params = {
          captchaCode: this.loginVerifyForm.captchaCode,
          loginId: this.loginId
        };
        sendLoginVericode(params)
          .then(() => {
            this.countdown();
            this.$message.success("短信发送成功");
            this.getRegisterCodeDisabled = true;
          })
          .catch(() => {
            this.getCaptchaCode();
          })
          .finally(() => {
            this.getRegisterCodeLoading = false;
          });
      }
    },
    // 发送短信倒计时
    countdown() {
      let sec = 120;
      this.timer = setInterval(() => {
        if (sec <= 0) {
          this.getRegisterCodeText = "获取验证码";
          this.getRegisterCodeDisabled = false;
          clearInterval(this.timer);
        } else {
          this.getRegisterCodeText = `重发(${sec--}s)`;
        }
      }, 1000);
    },
    submit() {
      this.$refs.form
        .validated()
        .then(() => {
          this.submitLoading = true;
          if (this.currentStatus === "register") {
            // 注册登录
            this.register(this.form)
              .then(res => {
                this.$router.push({
                  name: "spotmall",
                  params: { justLogin: true, loginData: res }
                });
                // this.setLoginInfo(res);
                this.$emit("registerSuccess");
              })
              .finally(() => {
                this.submitLoading = false;
              });
          } else {
            // 普通登录
            this.login({
              phone: this.form.phone,
              password: this.form.password,
              terminalFlag: 4
            })
              .then(res => {
                this.$router.push({
                  name: "spotmall",
                  params: { loginData: res }
                });
                // this.setLoginInfo(res);
                this.$emit("loginSuccess");
              })
              .catch(err => {
                // 需要进行登录认证
                if (err.code === this.$globalSite.errorCode.verifyByPhone) {
                  this.loginId = err.data.loginId;
                  this.loginVisible = true;
                  this.loginVerifyForm.phone = this.form.phone;
                  this.getCaptchaCode();
                }
              })
              .finally(() => {
                this.submitLoading = false;
              });
          }
        })
        .catch(() => {});
    },
    // 登录认证（短信认证登录）
    loginVerify() {
      this.$refs.loginVerify.validated().then(() => {
        this.submitLoading = true;
        this.verifyLogin({
          verifyCode: this.loginVerifyForm.registerCode,
          loginId: this.loginId,
          terminalFlag: 4
        })
          .then(res => {
            this.$router.push({ name: "spotmall", params: { loginData: res } });
            // this.setLoginInfo(res);
            this.$emit("loginSuccess");
          })
          .finally(() => {
            this.submitLoading = false;
          });
      });
    },
    // 完成重置密码
    resetPasswordFinish() {
      this.resetVisible = false;
    },
    loginVerifyClose() {
      // 清除定时器
      clearInterval(this.timer);
      this.timer = null;
      this.getRegisterCodeText = "获取验证码";
      this.getRegisterCodeDisabled = false;
      this.loginVerifyForm.captchaCode = null;
      this.loginVerifyForm.registerCode = null;
    },
    resetPasswordClose() {
      this.$refs.resetPassword.clearCountdown();
    }
    // // 给iframe添加加载状态
    // setLoginAgreementLoading() {
    //   this.loginAgreementLoading = true;
    //   let iframe = this.$refs.loginAgreement;
    //   const _this = this;
    //   if (iframe.attachEvent) {
    //     // IE
    //     iframe.attachEvent("onload", () => {
    //       _this.loginAgreementLoading = false;
    //     });
    //   } else {
    //     // 非IE
    //     iframe.onload = function() {
    //       _this.loginAgreementLoading = false;
    //     };
    //   }
    // }
  },
  created() {
    //   嵌套页默认显示登录界面
    this.currentStatus = this.isNesting ? "login" : this.$route.name;
    if (this.currentStatus === "register") {
      this.agreementVisible = true;
      // this.$nextTick(() => {
      //   this.setLoginAgreementLoading();
      // });
    }
  },
  mounted() {
    this.getCaptchaCode();
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/theme/color.scss";

.contents-register .c-form {
  ::v-deep .ant-form-item:nth-child(4),
  ::v-deep .ant-form-item:nth-child(5) {
    height: 0px;
    overflow: hidden;
    margin: 0;
  }
}
.contents {
  background-color: #fff;
  border-radius: 4px;
  padding: 25px 20px;
  .title {
    text-align: center;
    font-size: 22px;
    margin-bottom: 20px;
  }
  .submit {
    margin: 15px 0;
    .submit-space {
      .submit-btn {
        height: 40px;
      }
    }
  }
  .agreement {
    font-size: 14px;
    label {
      margin-right: 7px;
    }
  }
  .graphicCode {
    height: 32px;
    padding: 0 5px;
  }
  ::v-deep.ant-input-prefix .iconfont {
    @extend .primary;
  }
}
</style>

<style lang="scss">
.loginVerifyModal {
  .graphicCode {
    height: 32px;
    padding: 0 5px;
  }
  .ant-input-prefix .iconfont {
    color: var(--primary);
  }
}
</style>
